<?php if ( ! defined("BASEPATH")) exit("No direct script access allowed!");

/*!
 * Oemah Code MODEL
 * 
 * @package Oemah Code BACKBONE (APPLICATION CORE)
 * @COPYRIGHT OEMAHCODE
 * @author Ones Lynxs
 * @version 1.0
 * @access PUBLIC
 */
class OC_Model extends CI_Model {

	function fetch_rows()
	{
		$result = new stdClass();
		$result->success = TRUE;
		$result->rows    = array();
		$result->total   = 0;

		$query = $this->db->get();
		
		if ($query->num_rows() > 0)
		{
			$conn = clone($this->db);
			$result->total = $conn->query('SELECT FOUND_ROWS() total')->row()->total;
			$result->rows  = $query->result();
		}

		return $result;
	}

	function get_rows()
	{
		$query = $this->db->get();
		if ($query->num_rows() > 0)
			return $query->result();

		return array();
	}

	public function get_result($output = 'object')
	{
		$result = new stdClass();

		$result->success 	= TRUE;
		$result->data 		= array();
		$result->count 		= 0;
		$result->total 		= 0;

		if ($this->input->post('filter'))
		{
			$filter = $this->input->post('filter');
			
			foreach ($filter as $k => $v)
			{
				if ($v['data']['type'] == 'list' && strpos($v['data']['value'], ','))
				{
					$exp_value = explode(',', $v['data']['value']);

					for ($x = 0; $x < count($exp_value); $x++)
					{
						$this->db->or_where($v['field'], $exp_value[$x]);
					}
				}
				elseif ($v['data']['type'] == 'list') $this->db->where($v['field'], $v['data']['value']);
				else $this->db->like($v['field'], $v['data']['value']);
			}
		}
		if ($this->input->post('limit') !== FALSE && $this->input->post('limit') != 'All') $this->db->limit($this->input->post('limit'), $this->input->post('start'));
		if ($this->input->post('sort'))
		{
			$sort = json_decode($this->input->post('sort', TRUE));

			foreach ($sort as $k => $v)
			{
				$this->db->order_by($v->property, $v->direction);
			}
		}
		
		$qry = $this->db->get();

		if (($result->count = $qry->num_rows()) > 0)
		{
			$preg_replace	= preg_replace('/(.+?)LIMIT.+/is', '$1', $this->db->last_query());
			$result->total 	= $this->db->query($preg_replace)->num_rows();
			$result->data 	= ($output == "object") ? $qry->result() : $qry->result_array();
			
			$qry->free_result();
		}

		return $result;
	}
}